package com.none.web.service.book.impl;

import java.io.File;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.simple.ParameterizedBeanPropertyRowMapper;
import org.springframework.stereotype.Service;

import com.none.core.common.utils.DateUtil;
import com.none.core.common.utils.PathUtil;
import com.none.core.common.utils.QRCodeUtil;
import com.none.core.common.utils.StringUtil;
import com.none.core.exception.ValidateException;
import com.none.core.model.Pager;
import com.none.core.service.BaseServiceSupport;
import com.none.web.QRcode.constants.AppConstants;
import com.none.web.QRcode.util.AESUtil;
import com.none.web.common.bdPush.BaiduPushUtil;
import com.none.web.model.TBookcategory;
import com.none.web.model.TBookinfo;
import com.none.web.model.TBookreminder;
import com.none.web.model.TBookstat;
import com.none.web.model.TStaffpushinfo;
import com.none.web.model.TUserApp;
import com.none.web.service.book.IBookAppService;
import com.none.web.service.bookParam.IBookparamService;
@Service("bookAppService")
public class BookAppServiceImpl extends BaseServiceSupport implements IBookAppService {
	@Autowired
    JdbcTemplate jdbcTemplate;
	@Autowired
	IBookparamService bookParamService;
	@Autowired
	HttpServletRequest request;

	@Override
	public List<TBookinfo> queryBookList(Pager pager, String keywords,
			String category, String userName) throws Exception {
		//long timeStart = System.currentTimeMillis();
		//搜索关键字长度不能大于50个字符
		if(StringUtils.isNotBlank(keywords)){
			if(keywords.length()>50){
				throw new ValidateException("keywords.tooLong");
			}
		}
		//判断用户是否登录
		if (StringUtils.isBlank(userName)){
			throw new ValidateException("news.notIsLoginUser");
		}
		//判断用户是否存在
		if(getAppUserByUsername(userName)==null){
			throw new ValidateException("user.userUnExist");
		}
		
		//获取书的数量
		Integer totalRows = getBooksNums(keywords,category);
		if(totalRows==0){
			pager.setTotalPages(0);
			pager.setTotalRows(0);
			pager.setPageNo(1);
		}
		
		//设置总条数
		pager.setTotalRows(totalRows);
		//计算并设置总页数
		Integer pages=totalRows%pager.getPageSize()>0?pager.getTotalRows()/pager.getPageSize()+1:pager.getTotalRows()/pager.getPageSize();
		pager.setTotalPages(pages);
		
		//计算每次查询的开始位置
		Integer startNum = (pager.getPageNo()-1)*pager.getPageSize();
		Integer endNum = pager.getPageSize();
		
		StringBuffer sql = new StringBuffer();
		
		sql.append("select t.* from rgt_bookinfo t where t.book_open='Y' #category#  #keywords# order by t.addtime desc,t.book_Name desc limit "+startNum+", "+endNum); 
		String sql_ = sql.toString();
		//增加分类查询条件
		if(StringUtils.isNotBlank(category)&&!category.contains("all")){
			sql_=sql_.replace("#category#", " and t.catalog_id in ("+category+")");
		}else{
			sql_=sql_.replace("#category#", " ");
		}
		//增加关键字查询条件
		if(StringUtils.isNotBlank(keywords)){
			sql_=sql_.replace("#keywords#", " and (t.book_Name like '%"+keywords+"%' or t.book_Author like '%"+keywords+"%' or t.book_mgrNo like '%"+keywords+"%')");
		}else{
			sql_=sql_.replace("#keywords#", " ");
		}
		//查询数据
//		List<Map<String, Object>> listMap=this.jdbcTemplate.queryForList(sql_);
//		
//		List<TBookinfo> list = new ArrayList<TBookinfo>();
//		if(listMap!=null && listMap.size()>0){
//			for(int i=0;i<listMap.size();i++){
//				TBookinfo book = null;
//				book =findEntity(TBookinfo.class, Integer.parseInt(StringUtil.toString(listMap.get(i).get("book_sn"))));
//				
//				//设置书的可借数量
//				Integer avail = book.getBook_vol()-this.getAvaiBooksNums(book.getBook_mgrNo());
//				if(avail<0){
//					avail = 0;
//				}
//				book.setAvailable_quantity(avail);
//				list.add(book);
//			}
//		}
		
		
		RowMapper<TBookinfo> sr=ParameterizedBeanPropertyRowMapper.newInstance(TBookinfo.class); 
		List<TBookinfo> list=this.jdbcTemplate.query(sql_,sr);
		List<TBookinfo> list_ = new ArrayList<TBookinfo>();
		if(list!=null && list.size()>0){
			for(int i=0;i<list.size();i++){
				TBookinfo book = null;
				book =list.get(i);
				
				//设置书的可借数量
				Integer avail = book.getBook_vol()-this.getAvaiBooksNums(book.getBook_mgrNo());
				if(avail<0){
					avail = 0;
				}
				book.setAvailable_quantity(avail);
				list_.add(book);
			}
		}
		//long timeEnd = System.currentTimeMillis();
		//System.out.println(timeEnd-timeStart);
		return list_;
	}

	@Override
	public TBookinfo getDetailInfo(Integer bookId, String userName)
			throws Exception {
		//判断用户是否登录
		if (StringUtils.isBlank(userName)){
			throw new ValidateException("news.notIsLoginUser");
		}
		//判断用户是否存在
		if(getAppUserByUsername(userName)==null){
			throw new ValidateException("user.userUnExist");
		}
		//判断bookId是否为空
		String bookid = StringUtil.toString(bookId);
		if (StringUtils.isBlank(bookid)){
			throw new ValidateException("book.bookUnExist");
		}
		TBookinfo book = this.findEntity(TBookinfo.class, bookId);
		if(book==null){
			throw new ValidateException("book.bookUnExist");
		}else{
			//设置书的可借数量
			Integer avail = book.getBook_vol()-this.getAvaiBooksNums(book.getBook_mgrNo());
			if(avail<0){
				avail = 0;
			}
			book.setAvailable_quantity(avail);
			//设置书的类型
			TBookcategory category = this.findEntity(TBookcategory.class, book.getCatalog_id());
			book.setCategoryName(category.getCategory());
			
			//设置是否借过这本书
			int borrownums =getBorrowedBookByUsername(book.getBook_mgrNo(),userName);
			if(borrownums>0){
				book.setBorrowFlag(true);
			}else{
				book.setBorrowFlag(false);
			}
			
			//设置是否有预约或者没有还书的记录
			int record = getBorrowRecordByUsername(userName);
			if(record>0){
				book.setHaveBookFlag(true);
			}else{
				book.setHaveBookFlag(false);
			}
			//设置是否有提醒
			int reminderNums = getReminderByUsername(String.valueOf(book.getBook_sn()),userName);
			if(reminderNums>0){
				book.setHaveReminderFlag(true);
			}else{
				book.setHaveReminderFlag(false);
			}
			return book;
		}
	}
	
	@Override
	public Map<String,Object> getPickUpDate(String currentTime,String userName) throws Exception {
		//判断用户是否登录
		if (StringUtils.isBlank(userName)){
			throw new ValidateException("news.notIsLoginUser");
		}
		//判断用户是否存在
		if(getAppUserByUsername(userName)==null){
			throw new ValidateException("user.userUnExist");
		}
		
		Map<String,Object> map = new HashMap<String, Object>();
		
		String workDay = bookParamService.getParamByKey("workDay").getParam_value();
		String workTimeStart = bookParamService.getParamByKey("workTimeStart").getParam_value();
		String workTimeEnd = bookParamService.getParamByKey("workTimeEnd").getParam_value();
		List<Timestamp> pickList = DateUtil.getPickUpDate(workDay, workTimeStart, workTimeEnd, currentTime);
		
		map.put("pickDay", pickList);
		map.put("workTimeStart", workTimeStart);
		map.put("workTimeEnd", workTimeEnd);
		return map;
	}
	
	
	@Override
	public Map<String, Object> addBorrowBook(String book_mgrNo,String phone,String pickupday,String userName)
			throws Exception {
		//判断用户是否登录
		if (StringUtils.isBlank(userName)){
			throw new ValidateException("news.notIsLoginUser");
		}
		//判断用户是否存在
		TUserApp userapp = getAppUserByUsername(userName);
		if(userapp==null){
			throw new ValidateException("user.userUnExist");
		}
		//判断书存在不存在
		if(StringUtils.isBlank(book_mgrNo)){
			throw new ValidateException("book.bookUnExist");
		}
		
		TBookinfo book = getBooksByBook_mgrNo(book_mgrNo);
		if(book==null){
			throw new ValidateException("book.bookUnExist");
		}
		//电话不能为空
		if (StringUtils.isBlank(phone)){
			throw new ValidateException("book.phoneIsNull");
		}
		//预约取书日期不能为空
		if (StringUtils.isBlank(pickupday)){
			throw new ValidateException("book.pickupdayIsNull");
		}
		
		//判断还有没有可以借阅的书
		Integer avail = book.getBook_vol()-this.getAvaiBooksNums(book.getBook_mgrNo());
		if(avail<=0){
			throw new ValidateException("book.noBook");
		}
		
		//开始添加预约记录
		TBookstat  bookStat = new TBookstat();
		//获取登录人的邮箱
		String email = userapp.getEmail();
		bookStat.setBDetail_staffname(email.split("@")[0]);
		bookStat.setBDetail_staffNo(userapp.getUserId());
		bookStat.setBDetail_staffemail(email);
		bookStat.setBDetail_BookName(book.getBook_Name());
		bookStat.setBDetail_BookmgtNo(book.getBook_mgrNo());
		bookStat.setBDetail_RgtDate(new Timestamp(new Date().getTime()));
		if(StringUtils.isNotBlank(pickupday)&&!pickupday.equals("NaN")){
			Timestamp  t =new Timestamp(Long.valueOf(pickupday+"000"));
			String cfmDate = String.valueOf(t.getTime()+23*60*60*1000);
			bookStat.setBDetail_CfmDate(new Timestamp(Long.valueOf(cfmDate)));
		}
		bookStat.setBDetail_status(1);
		bookStat.setBDetail_RtnDate(null);
		bookStat.setBDetail_Susp("N");
		bookStat.setBDetail_Return("N");
		bookStat.setBDetail_BookSN(book.getBook_sn());
		bookStat.setBDetail_Tel(phone);
		bookStat.setBDetail_RelDate(null);
		bookStat.setBDetail_checkoutDate(null);
		bookStat.setBDetail_cancelDate(null);
		//组装Borrow_id
		String borrow = DateUtil.getYMDHMS()+StringUtil.randomNumbers(4);
		bookStat.setBorrow_id("Library"+borrow);//Library”+[YYYYMMDDHHMMSS]+[4 digit random number]
		bookStat.setUsername(userapp.getUserName());
		//生成二维码
		String serverPath = request.getSession().getServletContext().getRealPath("/");
		String picName = borrow+".png";
		String content = book.getBook_mgrNo()+AppConstants.QRCODER_SPLIT_CHAR+bookStat.getBorrow_id()+AppConstants.QRCODER_SPLIT_CHAR+book.getBook_sn()+AppConstants.QRCODER_SPLIT_CHAR+userName;
		
		bookStat.setBDetail_QRcode(PathUtil.getServerPath(request)+QRCodeUtil.genQrcode(serverPath.substring(0, (serverPath.length()-7)), content, picName, null));//二维码
		//保存数据
		if (saveEntity(bookStat) == null) {
			throw new ValidateException("common.illegalRequest");
		}
		
		Map<String, Object> map = new HashMap<String, Object>();
		//设置书的可借数量
		if(avail<0){
			avail = 0;
		}
		book.setAvailable_quantity(avail);
		map.put("bookInfo", book);
		
		String place = bookParamService.getParamByKey("place").getParam_value();
		String workTimeStart = bookParamService.getParamByKey("workTimeStart").getParam_value();
		String workTimeEnd = bookParamService.getParamByKey("workTimeEnd").getParam_value();
		map.put("place", place);
		map.put("workTimeStart", workTimeStart);
		map.put("workTimeEnd", workTimeEnd);
		map.put("pickupdate", bookStat.getBDetail_CfmDate());
		map.put("borrowId", bookStat.getBorrow_id());
		return map;
	}
	
	
	@Override
	public Map<String, Object> viewBorrowBook(String book_mgrNo,
			Integer bookId, String borrowId, String userName) throws Exception {
		//判断用户是否登录
		if (StringUtils.isBlank(userName)){
			throw new ValidateException("news.notIsLoginUser");
		}
		//判断用户是否存在
		TUserApp userapp = getAppUserByUsername(userName);
		if(userapp==null){
			throw new ValidateException("user.userUnExist");
		}
		//判断书存在不存在
		if(StringUtils.isBlank(book_mgrNo)){
			throw new ValidateException("book.bookUnExist");
		}
				
		TBookinfo book = getBooksByBook_mgrNo(book_mgrNo);
		if(book==null){
			throw new ValidateException("book.bookUnExist");
		}
		
		Map<String, Object> map = new HashMap<String, Object>();
		
		map.put("bookInfo", book);
		
		String place = bookParamService.getParamByKey("place").getParam_value();
		String workTimeStart = bookParamService.getParamByKey("workTimeStart").getParam_value();
		String workTimeEnd = bookParamService.getParamByKey("workTimeEnd").getParam_value();
		map.put("place", place);
		map.put("workTimeStart", workTimeStart);
		map.put("workTimeEnd", workTimeEnd);
		
		TBookstat bookStat = this.getBookStat(book_mgrNo, bookId, borrowId, userName);
		Timestamp  pickdate = bookStat.getBDetail_CfmDate();
		map.put("pickupdate", pickdate);
		map.put("QRcodeImage", bookStat.getBDetail_QRcode());
		map.put("borrowId", bookStat.getBorrow_id());
		
		Integer  status = bookStat.getBDetail_status();
		
		map.put("boprrowDate", bookStat.getBDetail_checkoutDate());
		
		Timestamp  dueDate = bookStat.getBDetail_RtnDate();
		map.put("dueDate", dueDate);
		map.put("userName", bookStat.getUsername());
		
		String workDay = bookParamService.getParamByKey("workDay").getParam_value();
		workDay = workDay.replace("1", "Mon").replace("2", "Tue").replace("3", "Wed").replace("4", "Thu").replace("5", "Fri").replace("6", "Sat").replace("7", "Sun");
		map.put("workDay", workDay);
		
		boolean flag = false;
		long pickdatetimes = bookStat.getBDetail_CfmDate().getTime();
		long nowtimes = new Date().getTime();
		//预约过期没拿书
		if(status == 1){
			if(pickdatetimes<nowtimes){
				flag = true;
			}
		}
		
		//拿书后还书到期日期前7天
		if(status == 2 || status == 3){
			long duetimes = bookStat.getBDetail_RtnDate().getTime();
			Timestamp before7 = DateUtil.stringToTimestamp(DateUtil.getBeforeSomeDayYYMMDDHHMMSS(DateUtil.timeStampToDate2(String.valueOf(duetimes)),-7));
			if(before7.getTime()<=nowtimes && nowtimes<=duetimes){
				flag = true;
			}
			if(duetimes<nowtimes){
				flag = true;
				bookStat.setBDetail_status(4);
				this.updateObj(bookStat);
			}
		}
		//过期
		if(status == 4){
			flag = true;
		}
		map.put("showMessage", flag);
		
		map.put("status", bookStat.getBDetail_status());
		return map;
	}
	
	
	@Override
	public boolean saveCancelBorrowBook(String book_mgrNo,
			Integer bookId, String borrowId, String userName) throws Exception {
		//判断用户是否登录
		if (StringUtils.isBlank(userName)){
			throw new ValidateException("news.notIsLoginUser");
		}
		//判断用户是否存在
		TUserApp userapp = getAppUserByUsername(userName);
		if(userapp==null){
			throw new ValidateException("user.userUnExist");
		}
		//判断书存在不存在
		if(StringUtils.isBlank(book_mgrNo)){
			throw new ValidateException("book.bookUnExist");
		}
		TBookstat bookStat = this.getBookStat(book_mgrNo, bookId, borrowId, userName);
		
		if(bookStat.getBDetail_status()==6){
			throw new ValidateException("book.hasBeenCanceled");
		}else if(bookStat.getBDetail_status()==2 ||bookStat.getBDetail_status()==3||bookStat.getBDetail_status()==4){
			throw new ValidateException("book.hasBeenCheckOut");
		}else if(bookStat.getBDetail_status()==5){
			throw new ValidateException("book.hasBeenCheckIn");
		}
		bookStat.setBDetail_cancelDate(new Timestamp(new Date().getTime()));
		bookStat.setBDetail_Return("Y");
		bookStat.setBDetail_status(6);
		this.updateObj(bookStat);
		
		
		//推送
		this.savePushReminder(bookId);
		return true;
	}
	
	
	@Override
	public Map<String, Object> readBorrowBook(String content, String userName)
			throws Exception {
		if (StringUtils.isBlank(content)) {
			throw new ValidateException("book.infoNotRight");
		}
		//判断用户是否登录
		if (StringUtils.isBlank(userName)){
			throw new ValidateException("news.notIsLoginUser");
		}
		//判断用户是否存在
		TUserApp userapp = getAppUserByUsername(userName);
		if(userapp==null){
			throw new ValidateException("user.userUnExist");
		}
		
		//解密
		content = AESUtil.decrypt(content,AppConstants.QR_CODER_AES_STATIC_KEY);
		String [] content_ = content.split(AppConstants.QRCODER_SPLIT_CHAR_ESCAPE);
		
		String book_mgrNo = content_[0];
		String borrowId = content_[1];
		Integer bookId = Integer.parseInt(content_[2]);
		String userName_ = content_[3];
		
		
		TBookstat bookStat = this.getBookStat(book_mgrNo, bookId, borrowId, userName_);
		if(bookStat.getBDetail_status()==5){
			throw new ValidateException("book.hasBeenCheckIn");
		}
		
		TBookinfo book = getBooksByBook_mgrNo(book_mgrNo);
		if(book==null){
			throw new ValidateException("book.bookUnExist");
		}
		
		Map<String, Object> map = new HashMap<String, Object>();
		
		map.put("bookInfo", book);
		
		String place = bookParamService.getParamByKey("place").getParam_value();
		String workTimeStart = bookParamService.getParamByKey("workTimeStart").getParam_value();
		String workTimeEnd = bookParamService.getParamByKey("workTimeEnd").getParam_value();
		map.put("place", place);
		map.put("workTimeStart", workTimeStart);
		map.put("workTimeEnd", workTimeEnd);
		map.put("borrower", userName_);
		map.put("staffId", bookStat.getBDetail_staffNo());
		map.put("pickupdate", bookStat.getBDetail_CfmDate());
		map.put("QRcodeImage", bookStat.getBDetail_QRcode());
		map.put("borrowId", bookStat.getBorrow_id());
		map.put("status", bookStat.getBDetail_status());
		map.put("boprrowDate", bookStat.getBDetail_checkoutDate());
		map.put("dueDate", bookStat.getBDetail_RtnDate());
		map.put("userName", bookStat.getUsername());
		return map;
	}
	
	
	@Override
	public Map<String,Object> saveCheckOutBook(String book_mgrNo,Integer bookId,String borrowId,String borrower,String userName) throws Exception {
		//判断用户是否登录
		if (StringUtils.isBlank(userName)){
			throw new ValidateException("news.notIsLoginUser");
		}
		//判断用户是否存在
		TUserApp userapp = getAppUserByUsername(userName);
		if(userapp==null){
			throw new ValidateException("user.userUnExist");
		}
		//判断书存在不存在
		if(StringUtils.isBlank(book_mgrNo)){
			throw new ValidateException("book.bookUnExist");
		}
		TBookstat bookStat = this.getBookStat(book_mgrNo, bookId, borrowId, borrower);
		if(bookStat.getBDetail_status()==2 || bookStat.getBDetail_status()==3 || bookStat.getBDetail_status()==4){
			throw new ValidateException("book.hasBeenCheckOut");
		}else if(bookStat.getBDetail_status()==5){
			throw new ValidateException("book.hasBeenCheckIn");
		}else if(bookStat.getBDetail_status()==6){
			throw new ValidateException("book.hasBeenCanceled");
		}
		//设置取书时间
		long times = new Date().getTime();
		Timestamp t = new Timestamp(times);
		bookStat.setBDetail_checkoutDate(t);
		//设置记录的状态
		bookStat.setBDetail_status(2);
		//设置预计到期还书时间
		bookStat.setBDetail_RtnDate(DateUtil.stringToTimestamp(DateUtil.getBeforeSomeDayYYMMDDHHMMSS(DateUtil.timeStampToDate2(String.valueOf(times)),30)));
		this.updateObj(bookStat);
		
		TBookinfo book = getBooksByBook_mgrNo(book_mgrNo);
		if(book==null){
			throw new ValidateException("book.bookUnExist");
		}
		Map<String, Object> map = new HashMap<String, Object>();
		
		map.put("bookInfo", book);
		
		String place = bookParamService.getParamByKey("place").getParam_value();
		String workTimeStart = bookParamService.getParamByKey("workTimeStart").getParam_value();
		String workTimeEnd = bookParamService.getParamByKey("workTimeEnd").getParam_value();
		map.put("place", place);
		map.put("workTimeStart", workTimeStart);
		map.put("workTimeEnd", workTimeEnd);
		map.put("borrower", bookStat.getBDetail_staffname());
		map.put("staffId", bookStat.getBDetail_staffNo());
		map.put("pickupdate", bookStat.getBDetail_CfmDate());
		map.put("QRcodeImage", bookStat.getBDetail_QRcode());
		map.put("borrowId", bookStat.getBorrow_id());
		map.put("status", bookStat.getBDetail_status());
		map.put("boprrowDate", bookStat.getBDetail_checkoutDate());
		map.put("dueDate", bookStat.getBDetail_RtnDate());
		map.put("userName", bookStat.getUsername());
		return map;
	}
	
	
	@Override
	public Map<String,Object> saveCheckInBook(String book_mgrNo,Integer bookId,String borrowId,String borrower,String userName) throws Exception {
		//判断用户是否登录
		if (StringUtils.isBlank(userName)){
			throw new ValidateException("news.notIsLoginUser");
		}
		//判断用户是否存在
		TUserApp userapp = getAppUserByUsername(userName);
		if(userapp==null){
			throw new ValidateException("user.userUnExist");
		}
		//判断书存在不存在
		if(StringUtils.isBlank(book_mgrNo)){
			throw new ValidateException("book.bookUnExist");
		}
		TBookstat bookStat = this.getBookStat(book_mgrNo, bookId, borrowId, borrower);
		
		if(bookStat.getBDetail_status()==5){
			throw new ValidateException("book.hasBeenCheckIn");
		}else if(bookStat.getBDetail_status()==6){
			throw new ValidateException("book.hasBeenCanceled");
		}else if(bookStat.getBDetail_status()==1){
			throw new ValidateException("book.checkout");
		}
		//设置还书时间
		long times = new Date().getTime();
		Timestamp t = new Timestamp(times);
		bookStat.setBDetail_RelDate(t);
		//设置记录的状态
		bookStat.setBDetail_status(5);
		//设置还书状态
		bookStat.setBDetail_Return("Y");
		this.updateObj(bookStat);
		
		TBookinfo book = getBooksByBook_mgrNo(book_mgrNo);
		if(book==null){
			throw new ValidateException("book.bookUnExist");
		}
		Map<String, Object> map = new HashMap<String, Object>();
		
		map.put("bookInfo", book);
		
		String place = bookParamService.getParamByKey("place").getParam_value();
		String workTimeStart = bookParamService.getParamByKey("workTimeStart").getParam_value();
		String workTimeEnd = bookParamService.getParamByKey("workTimeEnd").getParam_value();
		map.put("place", place);
		map.put("workTimeStart", workTimeStart);
		map.put("workTimeEnd", workTimeEnd);
		map.put("borrower", bookStat.getBDetail_staffname());
		map.put("staffId", bookStat.getBDetail_staffNo());
		map.put("pickupdate", bookStat.getBDetail_CfmDate());
		map.put("QRcodeImage", bookStat.getBDetail_QRcode());
		map.put("borrowId", bookStat.getBorrow_id());
		map.put("status", bookStat.getBDetail_status());
		map.put("boprrowDate", bookStat.getBDetail_checkoutDate());
		map.put("dueDate", bookStat.getBDetail_RtnDate());
		map.put("userName", bookStat.getUsername());
		
		//推送
		this.savePushReminder(bookId);
		return map;
	}
	
	@Override
	public Map<String,Object> saveRenewBook(String book_mgrNo,Integer bookId,String borrowId,String userName) throws Exception {
		//判断用户是否登录
		if (StringUtils.isBlank(userName)){
			throw new ValidateException("news.notIsLoginUser");
		}
		//判断用户是否存在
		TUserApp userapp = getAppUserByUsername(userName);
		if(userapp==null){
			throw new ValidateException("user.userUnExist");
		}
		//判断书存在不存在
		if(StringUtils.isBlank(book_mgrNo)){
			throw new ValidateException("book.bookUnExist");
		}
		TBookstat bookStat = this.getBookStat(book_mgrNo, bookId, borrowId, userName);
		//已经还书的不能续借
		if(bookStat.getBDetail_status()==5){
			throw new ValidateException("book.hasBeenCheckIn");
		}else if(bookStat.getBDetail_status()==4){
			throw new ValidateException("book.cannotRenewOverdue");
		}else if(bookStat.getBDetail_status()==3){
			throw new ValidateException("book.hasBeenRenewed");
		}else if(bookStat.getBDetail_status()==6){
			throw new ValidateException("book.hasBeenCanceled");
		}else if(bookStat.getBDetail_status()==1){
			throw new ValidateException("book.checkout");
		}
		//设置还书时间
		long times = bookStat.getBDetail_RtnDate().getTime();
		//设置预计到期还书时间
		bookStat.setBDetail_RtnDate(DateUtil.stringToTimestamp(DateUtil.getBeforeSomeDayYYMMDDHHMMSS(DateUtil.timeStampToDate2(String.valueOf(times)),30)));
		//设置记录的状态
		bookStat.setBDetail_status(3);
		//设置是否续借
		bookStat.setBDetail_Susp("Y");
		this.updateObj(bookStat);
		
		TBookinfo book = getBooksByBook_mgrNo(book_mgrNo);
		if(book==null){
			throw new ValidateException("book.bookUnExist");
		}
		Map<String, Object> map = new HashMap<String, Object>();
		
		map.put("bookInfo", book);
		
		String place = bookParamService.getParamByKey("place").getParam_value();
		String workTimeStart = bookParamService.getParamByKey("workTimeStart").getParam_value();
		String workTimeEnd = bookParamService.getParamByKey("workTimeEnd").getParam_value();
		map.put("place", place);
		map.put("workTimeStart", workTimeStart);
		map.put("workTimeEnd", workTimeEnd);
		map.put("borrower", bookStat.getBDetail_staffname());
		map.put("staffId", bookStat.getBDetail_staffNo());
		map.put("pickupdate", bookStat.getBDetail_CfmDate());
		map.put("QRcodeImage", bookStat.getBDetail_QRcode());
		map.put("borrowId", bookStat.getBorrow_id());
		map.put("status", bookStat.getBDetail_status());
		map.put("boprrowDate", bookStat.getBDetail_checkoutDate());
		map.put("dueDate", bookStat.getBDetail_RtnDate());
		map.put("userName", bookStat.getUsername());
		return map;
	}
	
	
	@Override
	public Map<String, Object> getMycurrentBook(String userName)
			throws Exception {
		//判断用户是否登录
		if (StringUtils.isBlank(userName)){
			throw new ValidateException("news.notIsLoginUser");
		}
		//判断用户是否存在
		TUserApp userapp = getAppUserByUsername(userName);
		if(userapp==null){
			throw new ValidateException("user.userUnExist");
		}
		
		TBookstat bookStat = this.getBookStatByUsername(userName);
		if(null == bookStat){
			throw new ValidateException("book.haveNobooks");
		}
				
		TBookinfo book = getBooksByBook_mgrNo(bookStat.getBDetail_BookmgtNo());
		if(book==null){
			throw new ValidateException("book.bookUnExist");
		}
		Map<String, Object> map = new HashMap<String, Object>();
		Integer  status = bookStat.getBDetail_status();
		map.put("bookInfo", book);
			
		String place = bookParamService.getParamByKey("place").getParam_value();
		String workTimeStart = bookParamService.getParamByKey("workTimeStart").getParam_value();
		String workTimeEnd = bookParamService.getParamByKey("workTimeEnd").getParam_value();
		map.put("place", place);
		map.put("workTimeStart", workTimeStart);
		map.put("workTimeEnd", workTimeEnd);
		map.put("borrower", bookStat.getBDetail_staffname());
		map.put("staffId", bookStat.getBDetail_staffNo());
		map.put("pickupdate", bookStat.getBDetail_CfmDate());
		map.put("QRcodeImage", bookStat.getBDetail_QRcode());
		map.put("borrowId", bookStat.getBorrow_id());
		map.put("boprrowDate", bookStat.getBDetail_checkoutDate());
		map.put("dueDate", bookStat.getBDetail_RtnDate());
		map.put("userName", bookStat.getUsername());
		String workDay = bookParamService.getParamByKey("workDay").getParam_value();
		workDay = workDay.replace("1", "Mon").replace("2", "Tue").replace("3", "Wed").replace("4", "Thu").replace("5", "Fri").replace("6", "Sat").replace("7", "Sun");
		map.put("workDay", workDay);
		
		boolean flag = false;
		long pickdatetimes = bookStat.getBDetail_CfmDate().getTime();
		long nowtimes = new Date().getTime();
		//预约过期没拿书
		if(status == 1){
			if(pickdatetimes<nowtimes){
				flag = true;
			}
		}
		
		//拿书后还书到期日期前7天
		if(status == 2 || status == 3){
			long duetimes = bookStat.getBDetail_RtnDate().getTime();
			Timestamp before7 = DateUtil.stringToTimestamp(DateUtil.getBeforeSomeDayYYMMDDHHMMSS(DateUtil.timeStampToDate2(String.valueOf(duetimes)),-7));
			if(before7.getTime()<=nowtimes && nowtimes<=duetimes){
				flag = true;
			}
			if(duetimes<nowtimes){
				flag = true;
				bookStat.setBDetail_status(4);
				this.updateObj(bookStat);
			}
		}

		//过期
		if(status == 4){
			flag = true;
		}
		map.put("showMessage", flag);
		map.put("status", bookStat.getBDetail_status());
		return map;
	}
	
	@Override
	public boolean saveReminderNoBook(String book_mgrNo,String userName) throws Exception {
		//判断用户是否登录
		if (StringUtils.isBlank(userName)){
			throw new ValidateException("news.notIsLoginUser");
		}
		//判断用户是否存在
		TUserApp userapp = getAppUserByUsername(userName);
		if(userapp==null){
			throw new ValidateException("user.userUnExist");
		}
		if (StringUtils.isBlank(book_mgrNo)){
			throw new ValidateException("book.bookUnExist");
		}		
		TBookinfo book = getBooksByBook_mgrNo(book_mgrNo);
		if(book==null){
			throw new ValidateException("book.bookUnExist");
		}
		
		TStaffpushinfo push  = this.getPushinfoByUsername(userName);
		
		
		TBookreminder reminder = new TBookreminder();
		reminder.setStaffname(userName);
		reminder.setBooksn(book.getBook_sn());
		reminder.setBookName(book.getBook_Name());
		reminder.setStatus("N");
		if(push!=null){
			reminder.setUserID(push.getUserId());
			reminder.setChannelId(push.getChannelId());
			reminder.setDevicetype(push.getDevice_type());
		}else{
			reminder.setUserID("");
			reminder.setChannelId("");
			reminder.setDevicetype("");
		}
		
		reminder.setAddtime(new Timestamp(new Date().getTime()));
		//保存
		if (saveEntity(reminder) == null) {
			throw new ValidateException("common.illegalRequest");
		}else{
			return true;
		}
		
	}
	
	/**
	 * 查询书的数量  Add by Bing 2015-09-23
	 * @param keywords
	 * @param category
	 * @return
	 */
	private Integer getBooksNums(String keywords,String category){
		StringBuffer sql = new StringBuffer();
		sql.append("select count(t.book_sn) nums from rgt_bookinfo t where t.book_open='Y' #category#  #keywords#");
		String sql_=sql.toString();
		//增加分类查询条件
		if(StringUtils.isNotBlank(category)&&!category.contains("all")){
			sql_=sql_.replace("#category#", " and t.catalog_id in ("+category+")");
		}else{
			sql_=sql_.replace("#category#", " ");
		}
		
		//增加关键字查询条件
		if(StringUtils.isNotBlank(keywords)){
			sql_=sql_.replace("#keywords#", " and (t.book_Name like '%"+keywords+"%' or t.book_Author like '%"+keywords+"%' or t.book_mgrNo like '%"+keywords+"%')");
		}else{
			sql_=sql_.replace("#keywords#", " ");
		}
		
		List<Map<String, Object>> listMapIsLike=this.jdbcTemplate.queryForList(sql_);
		Integer amount=0;
		if(listMapIsLike!=null && listMapIsLike.size()>0){
			amount=StringUtil.toInteger(listMapIsLike.get(0).get("nums"));
		}else{
			amount=0;
		}
		return amount;
	}
	
	/**
	 * 查询借出去和预约的书的数量（取消预约的除外）  Add by Bing 2015-09-23
	 * @param book_mgrNo
	 * @return
	 */
	private Integer getAvaiBooksNums(String book_mgrNo){
		StringBuffer sql = new StringBuffer();
		sql.append("select count(t.BDetail_Sn) nums from rgt_bookstat t where  t.BDetail_BookmgtNo='"+book_mgrNo+"' and t.BDetail_Return='N' and t.BDetail_status<>'6'");
		List<Map<String, Object>> listMapIsLike=this.jdbcTemplate.queryForList(sql.toString());
		Integer amount=0;
		if(listMapIsLike!=null && listMapIsLike.size()>0){
			amount=StringUtil.toInteger(listMapIsLike.get(0).get("nums"));
		}else{
			amount=0;
		}
		return amount;
	}
	
	
	/**
	 * 根据用户名查询对应的用户是否存在  Add by Bing 2015-09-23
	 * @param book_mgrNo
	 * @return
	 */
	private TUserApp getAppUserByUsername(String username){
		TUserApp userapp = null;
		String sql="select *  from t_user_app t where t.user_name='"+username+"'";
		RowMapper<TUserApp> sr=ParameterizedBeanPropertyRowMapper.newInstance(TUserApp.class); 
		List<TUserApp> list=this.jdbcTemplate.query(sql,sr);
		if(list!=null && list.size()>0){
			userapp =new TUserApp();
			userapp=list.get(0);
		}
		return userapp;
	}
	
	
	/**
	 * 根据用户名查询用户是否借过某本书  Add by Bing 2015-09-23
	 * @param book_mgrNo
	 * @return
	 */
	private Integer getBorrowedBookByUsername(String book_mgrNo,String username){
		StringBuffer sql = new StringBuffer();
		sql.append("select count(*) nums from rgt_bookstat t  where t.BDetail_Return='N' and t.BDetail_BookmgtNo='"+book_mgrNo+"' and t.username='"+username+"'");
		List<Map<String, Object>> listMapIsLike=this.jdbcTemplate.queryForList(sql.toString());
		Integer amount=0;
		if(listMapIsLike!=null && listMapIsLike.size()>0){
			amount=StringUtil.toInteger(listMapIsLike.get(0).get("nums"));
		}else{
			amount=0;
		}
		return amount;
	}
	
	
	/**
	 * 根据用户名查询用户是否设置过提醒  Add by Bing 2015-09-23
	 * @param book_mgrNo
	 * @return
	 */
	private Integer getReminderByUsername(String book_sn,String username){
		StringBuffer sql = new StringBuffer();
		sql.append("select count(t.id) nums from rgt_reminder t where   t.status='N'  and t.booksn='"+book_sn+"' and t.staffname='"+username+"'");
		List<Map<String, Object>> listMapIsLike=this.jdbcTemplate.queryForList(sql.toString());
		Integer amount=0;
		if(listMapIsLike!=null && listMapIsLike.size()>0){
			amount=StringUtil.toInteger(listMapIsLike.get(0).get("nums"));
		}else{
			amount=0;
		}
		return amount;
	}
	
	/**
	 * 根据用户名查询用户是否有预约或者未还的书  Add by Bing 2015-09-23
	 * @param book_mgrNo
	 * @return
	 */
	private Integer getBorrowRecordByUsername(String username){
		StringBuffer sql = new StringBuffer();
		sql.append("select count(*) nums from rgt_bookstat t  where t.BDetail_Return='N' and t.username='"+username+"'");
		List<Map<String, Object>> listMapIsLike=this.jdbcTemplate.queryForList(sql.toString());
		Integer amount=0;
		if(listMapIsLike!=null && listMapIsLike.size()>0){
			amount=StringUtil.toInteger(listMapIsLike.get(0).get("nums"));
		}else{
			amount=0;
		}
		return amount;
	}

	/**
	 * 根据book_mgrNo查询书的信息  Add by Bing 2015-09-23
	 * @param book_mgrNo
	 * @return
	 */
	private TBookstat getBookStat(String book_mgrNo,Integer bookId, String borrowId, String userName){
		TBookstat bookStat = null;
		String sql="select * from rgt_bookstat t where t.BDetail_BookmgtNo='"+book_mgrNo+"' and t.BDetail_BookSN='"+bookId+"' and t.borrow_id='"+borrowId+"' and t.username='"+userName+"' ";
		RowMapper<TBookstat> sr=ParameterizedBeanPropertyRowMapper.newInstance(TBookstat.class); 
		List<TBookstat> list=this.jdbcTemplate.query(sql,sr);
		if(list!=null && list.size()>0){
			bookStat =new TBookstat();
			bookStat=list.get(0);
		}
		return bookStat;
	}
	
	/**
	 * 根据book_mgrNo查询书的信息  Add by Bing 2015-09-23
	 * @param book_mgrNo
	 * @return
	 */
	private TBookstat getBookStatByUsername(String userName){
		TBookstat bookStat = null;
		String sql="select * from rgt_bookstat t where t.BDetail_Return='N' and  t.username='"+userName+"' ";
		RowMapper<TBookstat> sr=ParameterizedBeanPropertyRowMapper.newInstance(TBookstat.class); 
		List<TBookstat> list=this.jdbcTemplate.query(sql,sr);
		if(list!=null && list.size()>0){
			bookStat =new TBookstat();
			bookStat=list.get(0);
		}
		return bookStat;
	}
	
	/**
	 * 根据book_mgrNo查询书的信息  Add by Bing 2015-09-23
	 * @param book_mgrNo
	 * @return
	 */
	private TBookinfo getBooksByBook_mgrNo(String book_mgrNo){
		TBookinfo book = null;
		String sql="select * from rgt_bookinfo t where t.book_mgrNo='"+book_mgrNo+"'";
		RowMapper<TBookinfo> sr=ParameterizedBeanPropertyRowMapper.newInstance(TBookinfo.class); 
		List<TBookinfo> list=this.jdbcTemplate.query(sql,sr);
		if(list!=null && list.size()>0){
			book =new TBookinfo();
			book=list.get(0);
		}
		return book;
	}
	
	
	/**
	 * 根据用户名查询用户对应的百度云推送相关参数信息  Add by Bing 2015-09-23
	 * @param userName
	 * @return
	 */
	private TStaffpushinfo getPushinfoByUsername(String userName){
		TStaffpushinfo push = null;
		String sql="select * from t_staff_push_info t where t.username='"+userName+"'";
		RowMapper<TStaffpushinfo> sr=ParameterizedBeanPropertyRowMapper.newInstance(TStaffpushinfo.class); 
		List<TStaffpushinfo> list=this.jdbcTemplate.query(sql,sr);
		if(list!=null && list.size()>0){
			push =new TStaffpushinfo();
			push=list.get(0);
		}
		return push;
	}
	@Override
	public void savePushReminder(Integer bookId) throws Exception {
		List<TBookreminder> list = this.getPushList(bookId);
		if(list!=null && list.size()>0){
			TBookreminder reminder  = null;
			for(int i=0;i<list.size();i++){
				reminder = list.get(i);
				String baiduUserID = reminder.getUserID();
				String type = reminder.getDevicetype();
				String title = "Your preferred book is available now! ["+reminder.getBookName()+"]";
				if(baiduUserID !=null && !"".equals(baiduUserID)){
					if("ios".equals(type)){
						BaiduPushUtil.push_bd(title, "", type, baiduUserID,"reminder", bookId+"");
					}else{
						BaiduPushUtil.push_bd(title, " ", type, baiduUserID, "reminder", bookId+"");
					}
				}
				
				//推送完成后设置原纪录为已推送
				reminder.setStatus("Y");
				this.updateObj(reminder);
			}
		}
		
		
	}

	@Override
	public void pushBeforeDueOrAfterDue() throws Exception {
		System.out.println("推送定时任务执行开始"+DateUtil.getDateTime());
		//获取过期前几天、过期后几天提醒
		String beforeDay_dueDay = bookParamService.getParamByKey("dueBeforeSomeDay").getParam_value();
		String afterDay_dueDay = bookParamService.getParamByKey("overDuesomeDay").getParam_value();
		//9月30日过期后1天，10月2日中午12点推送信息告诉用户已经过期了。如果这个1天被配置为0天，就在10月1日中午推送信息
		int days =Integer.parseInt(afterDay_dueDay)*(-1)-1;
		afterDay_dueDay=days+"";
		
		
		RowMapper<TBookstat> sr=ParameterizedBeanPropertyRowMapper.newInstance(TBookstat.class); 
		//过期前7天得
		StringBuffer sql =new StringBuffer();
		sql.append("select * from rgt_bookstat td  where td.BDetail_status in('2','3') and  cast(((unix_timestamp(td.BDetail_RtnDate)-unix_timestamp(NOW()))/(24*60*60)) as signed)='"+beforeDay_dueDay+"' ");
		
		List<TBookstat> list=this.jdbcTemplate.query(sql.toString(),sr);
		if(list!=null && list.size()>0){
			for(int i=0;i<list.size();i++){
				//获取纪录中书的ID
				Integer bookId = list.get(i).getBDetail_BookSN();
				//获取纪录对应用户的百度推送相关信息
				String userId = list.get(i).getBDetail_staffNo();
				TUserApp userapp = this.findEntity(TUserApp.class, userId);
				TStaffpushinfo push = this.getTStaffpushinfoByUsername(userapp.getUserName());
				//推送
				String baiduUserID = push.getUserId();
				
				//System.out.println("baiduUserID "+i+"=="+baiduUserID);
				
				String type = push.getDevice_type();
				if(baiduUserID !=null && !"".equals(baiduUserID)){
					if("ios".equals(type)){
						BaiduPushUtil.push_bd("Your loan book is about to overdue, back to Book² to find more information.", "", type, baiduUserID,"currentBook", bookId+"");
						//System.out.println("推送定时任务执行结束IOS"+DateUtil.getDateTime());
					}else{
						BaiduPushUtil.push_bd("Your loan book is about to overdue, back to Book² to find more information.", " ", type, baiduUserID, "currentBook", bookId+"");
						//System.out.println("推送定时任务执行结束Android"+DateUtil.getDateTime());
					}
				}
			}
		}
		//过期后几天的
		String overdue = "select * from rgt_bookstat td  where td.BDetail_status in('2','3') and  cast(((unix_timestamp(td.BDetail_RtnDate)-unix_timestamp(NOW()))/(24*60*60)) as signed)='"+afterDay_dueDay+"' ";
		List<TBookstat> list_over=this.jdbcTemplate.query(overdue,sr);
		if(list_over!=null && list_over.size()>0){
			for(int i=0;i<list_over.size();i++){
				//获取纪录中书的ID
				Integer bookId = list_over.get(i).getBDetail_BookSN();
				//获取纪录对应用户的百度推送相关信息
				String userId = list_over.get(i).getBDetail_staffNo();
				TUserApp userapp = this.findEntity(TUserApp.class, userId);
				TStaffpushinfo push = this.getTStaffpushinfoByUsername(userapp.getUserName());
				//推送
				String baiduUserID = push.getUserId();
				
				//System.out.println("baiduUserID "+i+"=="+baiduUserID);
				
				String type = push.getDevice_type();
				if(baiduUserID !=null && !"".equals(baiduUserID)){
					if("ios".equals(type)){
						BaiduPushUtil.push_bd("Your loan book is overdue, please return the book in time.", "", type, baiduUserID,"currentBook", bookId+"");
						//System.out.println("推送定时任务执行结束IOS"+DateUtil.getDateTime());
					}else{
						BaiduPushUtil.push_bd("Your loan book is overdue, please return the book in time.", " ", type, baiduUserID, "currentBook", bookId+"");
						//System.out.println("推送定时任务执行结束Android"+DateUtil.getDateTime());
					}
				}
			}
		}
	}
	
	/**
	 * 查询要推送的列表  Add by Bing 2015-09-23
	 * @return
	 */
	private List<TBookreminder> getPushList(Integer booksn){
		String sql="select * from rgt_reminder t  where   t.status='N' and t.booksn='"+booksn+"' order by t.addtime asc";
		RowMapper<TBookreminder> sr=ParameterizedBeanPropertyRowMapper.newInstance(TBookreminder.class); 
		List<TBookreminder> list=this.jdbcTemplate.query(sql,sr);
		if(list==null){
			list = new ArrayList<TBookreminder>();
		}
		return list;
	}

	@Override
	public void deleteQRImageAfterCancel() throws Exception {
		System.out.println("清空二维码定时任务执行"+DateUtil.getDateTime());
		List<TBookstat> list = this.getAllCancelRecord();
		TBookstat stat = null;
		if(list!=null && list.size()>0){
			for(int i=0;i<list.size();i++){
				stat =new TBookstat();
				stat = list.get(i);
				String filepath = stat.getBDetail_QRcode();
				filepath =  filepath.replace(PathUtil.getServerPath(request), "");
				//System.out.println(" "+filepath);
				
				String contentpath = request.getServletContext().getRealPath("/");
				contentpath = contentpath.substring(0, (contentpath.length()-7));
				//文件的物理路径
				String path_temp = contentpath+filepath;
				//System.out.println("文件的物理路径=== "+path_temp);
				File file = new File(path_temp);
				if(file.exists()){
					//删除文件
					file.delete();
					stat.setBDetail_QRcode(null);
					this.updateObj(stat);
				}
			}	
		}
		
	}
	/**
	 * 查询已经取消的预约记录  Add by Bing 2015-09-23
	 * @return
	 */
	private List<TBookstat> getAllCancelRecord(){
		String sql="select * from rgt_bookstat t where t.BDetail_QRcode is not null and t.BDetail_status in('5','6')";
		RowMapper<TBookstat> sr=ParameterizedBeanPropertyRowMapper.newInstance(TBookstat.class); 
		List<TBookstat> list=this.jdbcTemplate.query(sql,sr);
		if(list==null){
			list = new ArrayList<TBookstat>();
		}
		return list;
	}
	
	/**
	 * 根据用户名查询用户的百度推送相关参数
	 * @param username
	 * @return
	 */
	private TStaffpushinfo getTStaffpushinfoByUsername(String username){
		String sql="select * from t_staff_push_info t where t.username='"+username+"'";
		RowMapper<TStaffpushinfo> sr=ParameterizedBeanPropertyRowMapper.newInstance(TStaffpushinfo.class); 
		List<TStaffpushinfo> list=this.jdbcTemplate.query(sql,sr);
		TStaffpushinfo push =null;
		if(list==null){
			push = new TStaffpushinfo();
		}else{
			push = list.get(0);
		}
		return push;
	}

	@Override
	public boolean checkStatus(String book_mgrNo,Integer bookId, String borrowId, String userName, String type) throws Exception {
		//判断用户是否登录
		if (StringUtils.isBlank(userName)){
			throw new ValidateException("news.notIsLoginUser");
		}
		//判断用户是否存在
		TUserApp userapp = getAppUserByUsername(userName);
		if(userapp==null){
			throw new ValidateException("user.userUnExist");
		}
				
		TBookstat bookStat = this.getBookStat(book_mgrNo, bookId, borrowId, userName);
		if(null == bookStat){
			throw new ValidateException("book.haveNobooks");
		}
		if("in".equals(type)){
			if(bookStat.getBDetail_status()==5){
				throw new ValidateException("book.hasBeenCheckIn");
			}
		}else{
			if(bookStat.getBDetail_status()==2){
				throw new ValidateException("book.hasBeenCheckOut");
			}
		}
		return true;
	}

}
